import { ref } from 'vue'
import app from '@/app'
import clientModel from './index'
import { get, update, del } from '@/api/erp/client_classify'

import base from '@/app/model'

// 继承总模型
const model = new base;

model.get = () => {
  return new Promise((resolve, jeject) => {
    app.ui.loading()
    get().then(res => {
      model.setList(res)
      // 更新数据
      model.idFilter()
      resolve(res)
    }).catch(res => {
      jeject(res)
    }).finally(() => {
      app.ui.loadingClose()
    })
  })
}

model.update = (...arge) => {
  return new Promise((resolve, jeject) => {
    update(...arge).then(res => {
      model.get()
      app.ui.message('success', res.message)
      resolve(res)
    }).catch(res => {
      app.ui.message('error', 'error.' + res.message)
      jeject(res)
    })
  })
}

model.del = () => {
  return new Promise((resolve, jeject) => {
    del(model.getId()).then(res => {
      model.get()
      // 选择到全部上
      model.select(0)
      app.ui.message('success', res.message)
      resolve(res)
    }).catch(res => {
      app.ui.message('error', 'error.' + res.message)
      jeject(res)
    })
  })
}

// 选择ID
model.id = ref('all')

// 获取ID
model.getId = () => {
  return model.id.value
}

// 筛选数据
model.idFilter = () => {
  // 设置数据
  model.setData(model.getList().find(item => item.id == model.getId()))
}

// 选择数据
model.select = id => {
  model.id.value = id.toString()
  model.idFilter()

  // 加载条件列表
  clientModel.getData().classify_id = id == 'all' ? null : id
  clientModel.page(1)
}

export default model